#include "TextureManager.h"
#include "SDL_image.h"


TextureManager* TextureManager::s_pInstance = nullptr; 


bool TextureManager::loadTexture(std::string file_name, std::string id, SDL_Renderer* pRenderer)
{
    SDL_Surface* p_TempSurface = IMG_Load(file_name.c_str()); 

	if (p_TempSurface == nullptr)
	{
	    //std::cout << IMG_GetError(); 
		return false; 
	}
	
	SDL_Texture* pTexture = SDL_CreateTextureFromSurface(pRenderer, p_TempSurface); 
	
	SDL_FreeSurface(p_TempSurface); 
	
	if (pTexture) 
	{
	    m_textureMap[id] = pTexture; 
		return true; 
	}
	
	return false; 
}


void TextureManager::Draw(std::string id, int x, int y, int width, int height, 
                          SDL_Renderer* pRenderer, SDL_RendererFlip flip)
{
    SDL_Rect src_rect, dest_rect; 
	
	src_rect.x  = src_rect.y = 0; 
	src_rect.w  = dest_rect.w = width; 
	src_rect.h  = dest_rect.h = height; 
	dest_rect.x = x; 
	dest_rect.y = y; 
	
	SDL_RenderCopyEx(pRenderer, m_textureMap[id], &src_rect, &dest_rect, 0, nullptr, flip); 
}


void TextureManager::drawFrame(std::string id, int x, int y, int width, int height, int current_row, int current_frame, SDL_Renderer* pRenderer, SDL_RendererFlip flip)
{
    SDL_Rect src_rect, dest_rect; 
	
	src_rect.x  = width  * current_frame; 
	src_rect.y  = height * (current_row - 1); 
	src_rect.w  = dest_rect.w = width; 
	src_rect.h  = dest_rect.h = height; 
	dest_rect.x = x; 
	dest_rect.y = y; 
	
	SDL_RenderCopyEx(pRenderer, m_textureMap[id], &src_rect, &dest_rect, 0, nullptr, flip); 
}
	